// 安全设置页面
const auth = require('../../utils/auth.js');
// 统一：弃用 config.baseUrl，改用 app.globalData.apiBaseUrl (已包含 /api/miniprogram 前缀)
// const config = require('../../utils/config');

Page({
  data: {
    userInfo: {},
    loading: true,
    modifyingPassword: false,
    showPasswordModal: false,
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
    
    // 安全状态
    securityStatus: {
      hasPassword: false,
      hasPhone: false,
      loginDevices: 0,
      lastLoginTime: ''
    }
  },

  onLoad: function() {
    this.loadUserInfo();
    this.loadSecurityStatus();
  },

  // 加载用户信息
  loadUserInfo: function() {
  const userInfo = auth.getCurrentUser && auth.getCurrentUser();
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        loading: false
      });
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载安全状态
  loadSecurityStatus: function() {
    wx.request({
      url: `${getApp().globalData.apiBaseUrl}/user/security-status`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${auth.getToken()}`
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          this.setData({
            securityStatus: res.data.data
          });
        }
      },
      fail: (error) => {
        console.error('加载安全状态失败:', error);
      }
    });
  },

  // 修改密码
  showChangePassword: function() {
    this.setData({
      showPasswordModal: true,
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
  },

  // 隐藏密码修改弹窗
  hidePasswordModal: function() {
    this.setData({
      showPasswordModal: false
    });
  },

  // 输入旧密码
  onOldPasswordInput: function(e) {
    this.setData({
      oldPassword: e.detail.value
    });
  },

  // 输入新密码
  onNewPasswordInput: function(e) {
    this.setData({
      newPassword: e.detail.value
    });
  },

  // 输入确认密码
  onConfirmPasswordInput: function(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },

  // 确认修改密码
  confirmChangePassword: function() {
    const { oldPassword, newPassword, confirmPassword } = this.data;

    // 验证输入
    if (!oldPassword || !newPassword || !confirmPassword) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    if (newPassword.length < 6) {
      wx.showToast({
        title: '新密码至少6位',
        icon: 'none'
      });
      return;
    }

    if (newPassword !== confirmPassword) {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'none'
      });
      return;
    }

    this.setData({ modifyingPassword: true });

    wx.request({
      url: `${getApp().globalData.apiBaseUrl}/user/password`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${auth.getToken()}`,
        'Content-Type': 'application/json'
      },
      data: {
        oldPassword: oldPassword,
        newPassword: newPassword
      },
      success: (res) => {
        this.setData({ modifyingPassword: false });
        
        if (res.statusCode === 200 && res.data.code === 0) {
          wx.showToast({
            title: '密码修改成功',
            icon: 'success'
          });
          this.hidePasswordModal();
        } else {
          wx.showToast({
            title: res.data.message || '修改失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        this.setData({ modifyingPassword: false });
        console.error('修改密码失败:', error);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 绑定手机号
  bindPhone: function() {
    if (!auth.isLoggedIn()) {
      wx.showToast({ title: '请先登录', icon: 'error' });
      return;
    }
    // 简单弹窗输入手机号，提交后端 /user/bind_mobile
    wx.showModal({
      title: '绑定手机号',
      editable: true,
      placeholderText: '输入手机号',
      success: (res) => {
        if (!res.confirm || !res.content) return;
        const mobile = res.content.trim();
        if (!/^\d{6,15}$/.test(mobile)) {
          wx.showToast({ title: '格式不正确', icon: 'error' });
          return;
        }
        wx.request({
          url: `${getApp().globalData.apiBaseUrl}/user/bind_mobile`,
          method: 'POST',
          header: { 'Authorization': `Bearer ${auth.getToken()}`, 'Content-Type': 'application/json' },
          data: { mobile },
          success: (r) => {
            if (r.statusCode === 200 && r.data && r.data.success) {
              // 更新本地缓存
              const cached = auth.getCurrentUser && auth.getCurrentUser();
              const merged = { ...(cached || {}), phone: mobile, mobile };
              wx.setStorageSync('userInfo', merged);
              this.setData({ 'userInfo.phone': mobile });
              wx.showToast({ title: '绑定成功', icon: 'success' });
            } else {
              wx.showToast({ title: (r.data && r.data.message) || '绑定失败', icon: 'error' });
            }
          },
          fail: () => wx.showToast({ title: '请求失败', icon: 'error' })
        });
      }
    });
  },

  // 查看登录设备
  viewLoginDevices: function() {
    wx.showToast({
      title: '登录设备管理开发中',
      icon: 'none'
    });
  },

  // 退出登录
  logout: function() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          auth.logout();
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/profile/profile'
            });
          }, 1500);
        }
      }
    });
  },

  // 注销账户
  deleteAccount: function() {
    wx.showModal({
      title: '注销账户',
      content: '注销后将无法恢复账户数据，确定要注销吗？',
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          // 这里应该有二次确认流程
          wx.showToast({
            title: '账户注销功能开发中',
            icon: 'none'
          });
        }
      }
    });
  }
});
